/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package pub.devrel.easypermissions.sample.slice;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.bundle.AbilityInfo;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.security.SystemPermission;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;

import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionDialog;
import pub.devrel.easypermissions.sample.MainAbility;
import pub.devrel.easypermissions.sample.ResourceTable;

/**
 * 权限申请
 *
 * @since 2021-03-05
 */
public class MainAbilitySlice extends AbilitySlice implements EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");

    private static final int RC_CAMERA_PERM = 123;
    private static final int RC_LOCATION_CONTACTS_PERM = 124;
    private static final int RC_SMS_PERM = 122;
    private static final int REQUEST_SETTING = 300;

    private static final String[] LOCATION_AND_CONTACTS =
        {SystemPermission.LOCATION, SystemPermission.WRITE_USER_STORAGE};

    private static final String YES = "yes";
    private static final String NO = "no";
    private Context mContext;
    private Ability mAbility;
    private static DirectionalLayout directionalLayout;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        ((MainAbility) getAbility()).setAbilitySlice(this);
        mContext = getContext();
        mAbility = getAbility();
        HiLog.info(TAG, "onStart");
        findComponentById(ResourceTable.Id_btn1).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                HiLog.info(TAG, "相机权限");
                cameraTask();
            }
        });

        findComponentById(ResourceTable.Id_btn2).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                HiLog.info(TAG, "定位和通讯录权限");
                locationAndContactsTask();
            }
        });

        findComponentById(ResourceTable.Id_btn3).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                HiLog.info(TAG, "SMS权限");
                smsTask();
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
        HiLog.info(TAG, "onActive");
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
        HiLog.info(TAG, "onForeground");
    }

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        super.onOrientationChanged(displayOrientation);
        HiLog.info(TAG, "onOrientationChanged");
    }

    @Override
    public Object getLastStoredDataWhenConfigChanged() {
        HiLog.info(TAG, "getLastStoredDataWhenConfigChanged");
        return super.getLastStoredDataWhenConfigChanged();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mContext = null;
        HiLog.info(TAG, "onStop");
    }

    @Override
    protected void onBackground() {
        super.onBackground();
        HiLog.info(TAG, "onBackground");
    }

    /**
     * 调用相机功能
     */
    public void cameraTask() {
        HiLog.info(TAG, "cameraTask");
        if (hasCameraPermission()) {
            // Have permission, do the thing!
            new ToastDialog(getContext()).setText("TODO: Camera things").show();
        } else {
            // Ask for one permission

            EasyPermissions.requestPermissions(this.getAbility(), getString(ResourceTable.String_rationale_camera),
                RC_CAMERA_PERM, SystemPermission.CAMERA);
        }
    }

    /**
     * 弹出提示dialog
     */
    //    @AfterPermissionGranted(RC_CAMERA_PERM)
    public void toast() {
        HiLog.info(TAG, "toast Camera things ");
        DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(mContext)
            .parse(ResourceTable.Layout_toast_layout, null, false);
        Text txt = (Text) toastLayout.findComponentById(ResourceTable.Id_msg_toast);
        txt.setText(mContext.getString(ResourceTable.String_returned_from_app_settings_to_ability,
            hasCameraPermission() ? YES : NO,
            hasLocationAndContactsPermissions() ? YES : NO,
            hasSmsPermission() ? YES : NO));
        new ToastDialog(mContext).setComponent(toastLayout).show();
    }

    /**
     * 是否有相机的权限
     *
     * @return 有true，反之false
     */
    public boolean hasCameraPermission() {
        HiLog.info(TAG, "hasCameraPermission = " + EasyPermissions.hasPermissions(this, SystemPermission.CAMERA));
        return EasyPermissions.hasPermissions(mAbility, SystemPermission.CAMERA);
    }

    /**
     * 调用定位功能
     */
    //    @AfterPermissionGranted(RC_LOCATION_CONTACTS_PERM)
    public void locationAndContactsTask() {
        if (hasLocationAndContactsPermissions()) {
            // Have permissions, do the thing!
            showToast(getContext(), "TODO: Location and Contacts things");
        } else {
            // Ask for both permissions
            EasyPermissions.requestPermissions(
                this.getAbility(),
                getString(ResourceTable.String_rationale_location_contacts),
                RC_LOCATION_CONTACTS_PERM,
                LOCATION_AND_CONTACTS);
        }
    }

    /**
     * 判断是否有定位权限
     *
     * @return 有 true 反之 false
     */
    public boolean hasLocationAndContactsPermissions() {
        return EasyPermissions.hasPermissions(mAbility, LOCATION_AND_CONTACTS);
    }

    /**
     * 调用短信的功能
     */
    //    @AfterPermissionGranted(RC_SMS_PERM)
    private void smsTask() {
        if (EasyPermissions.hasPermissions(this, SystemPermission.READ_MESSAGES)) {
            // Have permission, do the thing!
            HiLog.info(TAG, "TODO: SMS things");
        } else {
            // Request one permission
            EasyPermissions.requestPermissions(this.getAbility(), getString(ResourceTable.String_rationale_sms),
                RC_SMS_PERM, SystemPermission.READ_MESSAGES);
        }
    }

    /**
     * 是否有短信的权限
     *
     * @return 有 true 反之 false
     */
    public boolean hasSmsPermission() {
        return EasyPermissions.hasPermissions(this, SystemPermission.READ_MESSAGES);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        HiLog.info(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());
        String str = "TODO: somethings";
        switch (requestCode) {
            case RC_CAMERA_PERM:
                str = "TODO: Camera things";
                break;
            case RC_LOCATION_CONTACTS_PERM:
                str = "TODO: Location and Contacts things";
                break;
            case RC_SMS_PERM:
                str = "TODO: SMS things";
                break;
            default:
                break;
        }
        showToast(mContext, str);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        HiLog.info(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());

        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        String[] str = new String[perms.size()];
        for (int i = 0; i < perms.size(); i++) {
            HiLog.info(TAG, "onPermissionsDenied:perm = " + perms.get(i));
            str[i] = perms.get(i);
        }
        HiLog.info(TAG, "onPermissionsDenied:" + EasyPermissions.somePermissionPermanentlyDenied(mAbility, perms));
        if (EasyPermissions.somePermissionPermanentlyDenied(mAbility, perms)) {
            PermissionDialog dialog = new PermissionDialog(mContext, requestCode, str);
            dialog.setTitle("Permissions Required");
            dialog.setContent(getString(ResourceTable.String_dialog_content));
            dialog.setOnClickListener(new PermissionDialog.OnClickListener() {
                @Override
                public void ok(IDialog myDialog) {
                    Intent intent = new Intent();
                    intent.setAction(IntentConstants.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setUri(Uri.parse("package:" + mContext.getBundleName()));
                    mContext.startAbility(intent, REQUEST_SETTING);
                }

                @Override
                public void cancel(IDialog myDialog) {
                    toast();
                }
            });
            dialog.show();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        HiLog.info(TAG, "onRationaleAccepted:" + requestCode);
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        HiLog.info(TAG, "onRationaleDenied:" + requestCode);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
    }

    /**
     * 设置界面返回
     *
     * @param requestCode 返回码
     * @param permissions 申请的权限
     * @param grantResults 申请结果
     */
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        HiLog.info(TAG, "onRequestPermissionsResult:" + requestCode);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * toast
     *
     * @param context 上下文
     * @param content toast内容
     */
    public static void showToast(Context context, String content) {
        directionalLayout = new DirectionalLayout(context);
        DirectionalLayout.LayoutConfig config =
            new DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_PARENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        directionalLayout.setLayoutConfig(config);
        Text text = new Text(context);
        text.setLayoutConfig(config);
        text.setText(content);
        text.setTextAlignment(TextAlignment.CENTER);
        text.setTextSize(40);
        directionalLayout.addComponent(text);
        new ToastDialog(context).setComponent(directionalLayout).setAutoClosable(true).show();
    }
}
